package com.hzcx.app.simplechat.ui.home;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocationClient;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseFragment;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.chat.event.ChatListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.MainNumChangeEvent;
import com.hzcx.app.simplechat.ui.friend.FriendListByLableActivity;
import com.hzcx.app.simplechat.ui.group.GroupCreateActivity;
import com.hzcx.app.simplechat.ui.home.adapter.HomeMessageAdapter;
import com.hzcx.app.simplechat.ui.home.dao.ChatTopDao;
import com.hzcx.app.simplechat.ui.home.dialog.HomeMoreDialog;
import com.hzcx.app.simplechat.ui.home.event.ChatTopEvent;
import com.hzcx.app.simplechat.ui.publicui.CaptureActivity;
import com.hzcx.app.simplechat.ui.user.event.UserRemarkEvent;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements HomeMessageAdapter.OnHomeMessageListener, HXGroupMessageRefreshInterface {

    private final static int MSG_REFRESH = 2;
    private final static int MSG_REFRESH_ADAPTER_DATA = 0;

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.rv_msg)
    RecyclerView rvMsg;
    @BindView(R.id.ll_null)
    LinearLayout llNull;

    private List<EMConversation> listData;
    private HomeMessageAdapter messageAdapter;

    protected boolean hidden; // 当前界面是否隐藏
    protected boolean isConflict;

    @Override
    public int getLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void initView() {
        listData = new ArrayList<>();
        messageAdapter = new HomeMessageAdapter(R.layout.rv_item_chat_home, listData);
        rvMsg.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        rvMsg.setAdapter(messageAdapter);
    }

    @Override
    public void initData() {
        listData.addAll(ChatUtil.getInstance().loadConversationList());
        messageAdapter.notifyDataSetChanged();

        EMClient.getInstance().addConnectionListener(connectionListener);
        HXGroupMessageListener groupMessageListener = new HXGroupMessageListener();
        groupMessageListener.messageFragment = this;
        EMClient.getInstance().groupManager().addGroupChangeListener(groupMessageListener);

        messageAdapter.setOnHomeMessageListener(this);

        addHeader();
    }

    @OnClick({R.id.iv_more})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_more: // 更多
                showMoreDialog();
                break;
        }
    }

    /**
     * refresh ui
     * 刷新消息列表
     */
    public void refresh() {
        if (!handler.hasMessages(MSG_REFRESH)) {
            handler.sendEmptyMessage(MSG_REFRESH);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_REFRESH) {
                listData.clear();
                listData.addAll(ChatUtil.getInstance().loadConversationList());
                if (!handler.hasMessages(MSG_REFRESH_ADAPTER_DATA)) {
                    handler.sendEmptyMessage(MSG_REFRESH_ADAPTER_DATA);
                }
                if (listData == null || listData.size() <= 0) {
                    llNull.setVisibility(View.VISIBLE);
                } else {
                    llNull.setVisibility(View.GONE);
                }
            } else if (msg.what == MSG_REFRESH_ADAPTER_DATA) {
                messageAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
//        if (!hidden && !isConflict) {
//            refresh();
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!hidden) {
            refresh();
        }
    }

    protected EMConnectionListener connectionListener = new EMConnectionListener() {

        @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED
                    || error == EMError.USER_KICKED_BY_CHANGE_PASSWORD || error == EMError.USER_KICKED_BY_OTHER_DEVICE) {
                isConflict = true;
            } else {
                handler.sendEmptyMessage(0);
            }
        }

        @Override
        public void onConnected() {
            handler.sendEmptyMessage(1);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(connectionListener);
    }

    /**
     *  刷新消息列表
     */
    public void refreshMsg(){
        refresh();
    }

    /**
     * 删除会话
     *
     * @param pos
     */
    @Override
    public void delete(int pos) {
        EventBus.getDefault().post(new MainNumChangeEvent());
    }

    /**
     * 已读未读状态改变
     *
     * @param pos
     */
    @Override
    public void readChange(int pos) {
        EventBus.getDefault().post(new MainNumChangeEvent());
    }

    /**
     * 置顶
     *
     * @param pos
     */
    @Override
    public void toTop(int pos) {
        try {
            int userId = -1;
            EMMessage message = listData.get(pos).getLastMessage();
            if (message.direct() == EMMessage.Direct.SEND) {
                userId = message.getIntAttribute(ChatConstant.EXTRA_RECEIVE_USER_ID);
            } else {
                userId = message.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
            }
            if (listData.get(pos).getExtField().equals("toTop")) {
                listData.get(pos).setExtField("false");
                LitePal.deleteAll(ChatTopDao.class, "userId=" + userId);
            } else {
                listData.get(pos).setExtField("toTop");
                ChatTopDao dao = new ChatTopDao();
                dao.setUserId(userId);
                dao.save();
            }
            refresh();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息置顶改变
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void chatToTopChange(ChatTopEvent event) {
        try {
            for (int i = 0; i < listData.size(); i++) {
                EMConversation conversation = listData.get(i);
                EMMessage message = conversation.getLastMessage();
                int userId = -1;
                if (message.direct() == EMMessage.Direct.SEND) {
                    userId = message.getIntAttribute(ChatConstant.EXTRA_RECEIVE_USER_ID);
                } else {
                    userId = message.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
                }
                if (userId == event.getId()) {
                    if (event.isTop()) {
                        conversation.setExtField("toTop");
                        ChatTopDao dao = new ChatTopDao();
                        dao.setUserId(userId);
                        dao.save();
                    } else {
                        conversation.setExtField("false");
                        LitePal.deleteAll(ChatTopDao.class, "userId=" + userId);
                    }
                    refresh();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 有其他改动，刷新列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void chatListRefresh(ChatListRefreshEvent event) {
        refresh();
    }

    /**
     * 更多按钮
     */
    private void showMoreDialog() {
        HomeMoreDialog moreDialog = new HomeMoreDialog(getActivity(), new HomeMoreDialog.OnHomeMoreMenuListener() {
            @Override
            public void qrCode() {
                registerPermission();
            }

            @Override
            public void createGroup() {
                newGroup();
            }
        });
        moreDialog.show();
    }

    /**
     * 创建群组
     *
     */
    private void newGroup() {
        Intent intent = new Intent(getContext(), GroupCreateActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(FriendListByLableActivity.INTENT_LIST_BUNDLE, null);
        intent.putExtras(bundle);
        getContext().startActivity(intent);
    }

    /**
     * 申请相机权限
     */
    private void registerPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.CAMERA)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 权限申请失败
     */
    @PermissionFail(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openFail() {
        ToastUtils.show("权限获取失败，无法保存图片");
    }

    /**
     * 权限申请成功
     */
    @PermissionSuccess(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openSuccess() {
        startActivity(new Intent(getActivity(), CaptureActivity.class));
    }

    /**
     * 添加头部
     */
    private ConstraintLayout consSearch;

    private void addHeader() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_home_header, null);
        consSearch = view.findViewById(R.id.cons_search);

        consSearch.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), HomeSearchMsgActivity.class)));

        messageAdapter.addHeaderView(view);
    }

    /**
     * 备注名修改成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void remarkUpdateSuccess(UserRemarkEvent event) {
        messageAdapter.notifyDataSetChanged();
    }

    @Override
    public void groupRefresh(String groupHXID) {
        handler.sendEmptyMessage(MSG_REFRESH);
    }

    @Override
    public void groupMemberRemove(String groupID, String hxID) {
        handler.sendEmptyMessage(MSG_REFRESH);
    }

    @Override
    public void groupDestroyed(String groupID) {
        handler.sendEmptyMessage(MSG_REFRESH);
    }

}
